package com.ymm.controller;

import com.ymm.domain.entity.Role;
import com.ymm.domain.entity.RoleMenu;
import com.ymm.domain.vo.ResponseResult;
import com.ymm.enums.AppHttpCodeEnum;
import com.ymm.service.RoleMenuService;
import com.ymm.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author 椰咩咩咩
 * @version 1.0-SNAPSHOT
 * @date 2023/4/4 17:15
 * @Description
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private RoleService roleService;

    @Resource
    private RoleMenuService roleMenuService;

    @PreAuthorize("@ps.hasPermission('sys:role:list')")
    @GetMapping("/page")
    public ResponseResult pageRoles(
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(required = false) String roleName) {
        return roleService.pageRoles(pageNum, pageSize, roleName);
    }

    @PreAuthorize("@ps.hasPermission('sys:role:add')")
    @PostMapping
    public ResponseResult addRoles(@RequestBody Role role) {
        boolean b = roleService.save(role);
        return b ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.ADD_FAIL);
    }

    @PreAuthorize("@ps.hasPermission('sys:role:update')")
    @PutMapping
    public ResponseResult modifyRoles(@RequestBody Role role) {
        boolean b = roleService.updateById(role);
        return b ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.ADD_FAIL);
    }

    @PreAuthorize("@ps.hasPermission('sys:role:delete')")
    @DeleteMapping("/{id}")
    public ResponseResult removeRoles(@PathVariable Long id) {
        boolean b = roleService.removeById(id);
        return b ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.ADD_FAIL);
    }

    @PreAuthorize("@ps.hasPermission('sys:role:assign')")
    @PostMapping("/assign")
    public ResponseResult assign(@RequestBody RoleMenu roleMenu) {
        boolean b = roleMenuService.save(roleMenu);
        return b ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.ADD_FAIL);
    }

    @PreAuthorize("@ps.hasPermission('sys:user:role:not')")
    @GetMapping("/not/{id}")
    public ResponseResult userNotHasRoles(@PathVariable Long id) {
        return roleService.userNotHasRoles(id);
    }

    @PreAuthorize("@ps.hasPermission('sys:user:role:has')")
    @GetMapping("/has/{id}")
    public ResponseResult userHasRoles(@PathVariable Long id) {
        return roleService.userHasRoles(id);
    }

}
